//
//  YHOptionTagsView.m
//  ScriptKill
//
//  Created by 林宁宁 on 2021/3/31.
//  Copyright © 2021 优智汇. All rights reserved.
//

#import "YHOptionTagsView.h"
#import "UIScrollView+YHNoData.h"
#import "YHBaseCollectionViewCell.h"
#import "UIButton+YH.h"
#import "YHHUD.h"
#import "YHInputAlertView.h"
#import "UIView+YHAnimation.h"
#import "UIView+YHFrame.h"

@interface YHOptionTagsItem : YHBaseObject

@property (copy, nonatomic) NSString * tagID;
@property (copy, nonatomic) NSString * tag;
@property (retain, nonatomic) UIColor * _Nullable color;
@property (assign, nonatomic) BOOL isSelect;

@property (assign, nonatomic) BOOL isShowDeleteBtn;

@end
@implementation YHOptionTagsItem
@end

@implementation YHOptionTagsConfig
-(void)yh_commonInit{
    self.space = 5;
    self.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.selectTags = [NSMutableArray new];
    self.maxCount = 10000;
}
@end



@interface YHOptionTagsCell : YHBaseCollectionViewCell

@property (retain, nonatomic) UIButton * btnTitle;

@property (retain, nonatomic) UIButton * btnDelete;

@property (copy, nonatomic) void(^closeBlock)(NSIndexPath * passIndexPath);

@end

@implementation YHOptionTagsCell

-(void)yh_commonInit{
    self.cellContent.layer.masksToBounds = NO;
    self.contentView.clipsToBounds = NO;
    
    self.btnTitle = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnTitle.layer.cornerRadius = 5;
    self.btnTitle.layer.masksToBounds = YES;
    self.btnTitle.layer.borderColor = [UIColor yh_separator].CGColor;
    self.btnTitle.layer.borderWidth = 1;
    self.btnTitle.titleLabel.font = [UIFont yh_pfOfSize:10];
    self.btnTitle.userInteractionEnabled = NO;
    [self.contentView addSubview:self.btnTitle];
    [self.btnTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
    
    self.btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.btnDelete setImage:[UIImage imageNamed:@"close_mini"] forState:UIControlStateNormal];
    [self.btnDelete setBackgroundColor:[UIColor yh_black].yh_alpha(0.6)];
    self.btnDelete.layer.cornerRadius = 9;
    self.btnDelete.layer.masksToBounds = YES;
    self.btnDelete.yh_touchAreaInsets = UIEdgeInsetsMake(0, 20, 10, 0);
    [self.btnDelete addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.btnDelete];
    [self.btnDelete mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.btnTitle.mas_right);
        make.centerY.equalTo(self.btnTitle.mas_top);
        make.size.mas_equalTo(CGSizeMake(18, 18));
    }];
    self.btnDelete.hidden = YES;
}

- (void)closeAction{
    if(self.closeBlock){
        self.closeBlock(self.indexPath);
    }
}

@end


@interface YHOptionTagsView()<UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (retain, nonatomic) UICollectionView * collectionView;

@property (retain, nonatomic) NSMutableArray <YHOptionTagsItem *> * tags;

@property (retain, nonatomic, readwrite) YHOptionTagsConfig * config;

@property (retain, nonatomic) UILongPressGestureRecognizer * longPress;

@end

@implementation YHOptionTagsView


-(void)yh_commonInit{
    
    self.tags = [NSMutableArray new];
    self.userInteractionEnabled = NO;
    
    UICollectionViewFlowLayout * flowLayout = [UICollectionViewFlowLayout new];
 
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    [self.collectionView registerClass:YHOptionTagsCell.class forCellWithReuseIdentifier:YHOptionTagsCell.cellIndentify];
    
    [self.collectionView emptyConfig:^(YHDZNEmptyDelegate * _Nonnull delegate) {
        delegate.shouldShowEmpty = @(NO);
        delegate.title = @"";
    }];
    
    self.clipsToBounds = NO;
    self.collectionView.clipsToBounds = NO;
    
    WS(weakSelf)
    [self yh_kvoForKeyPath:@"contentSize" observe:self.collectionView block:^(id  _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        if(weakSelf.config.isAutoExpand){
            [weakSelf updateContentHeightLayout];
        }
        if(weakSelf.config.contentChangeBlock){
            weakSelf.config.contentChangeBlock(weakSelf.collectionView.contentSize);
        }
    }];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    if([self.superview isKindOfClass:[UIStackView class]]){
        [self updateContentHeightLayout];
    }
}

-(void)setConfig:(YHOptionTagsConfig *)config{
    _config = config;
    [self updateFlowLayout];
    
    if(config.isAutoExpand){
        [self updateContentHeightLayout];
    }else{
        self.collectionView.scrollEnabled = YES;
    }
    
    [self addLongPress];
}

- (void)addLongPress{
    if(self.longPress){
        return;
    }
    self.userInteractionEnabled = YES;
    
    self.longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGesture)];
    self.longPress.minimumPressDuration = 1;
    [self.collectionView addGestureRecognizer:self.longPress];
}

- (void)longGesture{
    if(!self.config.canLongpressToDelete){
        return;
    }
    if(self.longPress.state == UIGestureRecognizerStateBegan){
        CGPoint point = [self.longPress locationInView:self.collectionView];
        NSIndexPath * indexPath = [self.collectionView indexPathForItemAtPoint:point];
        if(self.config.addTagBlock && indexPath.row >= self.tags.count){
            return;
        }
        YHOptionTagsItem * tag = self.tags[indexPath.row];
        tag.isShowDeleteBtn = YES;
        [self.collectionView reloadData];
    }
}


- (void)reloadTagsView{
    [self.collectionView reloadData];
    if(self.config.isAutoExpand){
        [self updateContentHeightLayout];
    }
//    
//    if([self.superview isKindOfClass:[UIStackView class]]){
//        [self updateContentHeightLayout];
//    }
}

- (void)updateFlowLayout{
    UICollectionViewFlowLayout * flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.scrollDirection = self.config.scrollDirection;
    flowLayout.minimumInteritemSpacing = self.config.space;
    flowLayout.minimumLineSpacing = self.config.space;
    [self.collectionView setCollectionViewLayout:flowLayout animated:YES];
}

- (void)updateContentHeightLayout{
    self.collectionView.scrollEnabled = NO;
    if(CGRectGetHeight(self.frame) == 0){
        [self layoutSubviews];
    }
    CGSize contentSize = self.collectionView.contentSize;
    if(contentSize.height == 0){
        return;
    }
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(contentSize.height);
    }];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(self.config.addTagBlock){
        return self.tags.count + 1;
    }
    return self.tags.count;
}

-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YHOptionTagsCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:YHOptionTagsCell.cellIndentify forIndexPath:indexPath];
    cell.indexPath = indexPath;
    
    cell.btnTitle.layer.borderColor = [UIColor clearColor].CGColor;
    [cell.btnTitle setTitleColor:[UIColor yh_h1] forState:UIControlStateNormal];
    cell.btnTitle.layer.borderWidth = 0;
    
    UIColor * color = nil;
    NSString * tagStr = nil;
    
    if(indexPath.row == self.tags.count && self.config.addTagBlock){
        [cell.btnTitle setTitle:@"新增" forState:UIControlStateNormal];
    }else{
        YHOptionTagsItem * tag = self.tags[indexPath.row];
        [cell.btnTitle setTitle:tag.tag forState:UIControlStateNormal];
        if(tag.color){
            color = tag.color;
        }
        if(tag.isShowDeleteBtn){
            cell.btnDelete.hidden = NO;
        }else{
            cell.btnDelete.hidden = YES;
        }
        tagStr = tag.tag;
    }
    
    if(self.config.showStyle == YHOptionTagsStyle_Border){
        cell.btnTitle.layer.borderWidth = 1;
        if(color){
            cell.btnTitle.layer.borderColor = color.CGColor;
            [cell.btnTitle setTitleColor:color forState:UIControlStateNormal];
        }
        else if (self.config.tagColor){
            cell.btnTitle.layer.borderColor = [self.config.tagColor darkerColor:0.1].CGColor;
            [cell.btnTitle setTitleColor:self.config.tagColor forState:UIControlStateNormal];
        }
        else{
            cell.btnTitle.layer.borderColor = [[UIColor yh_hint] darkerColor:0.1].CGColor;
            [cell.btnTitle setTitleColor:[UIColor yh_hint] forState:UIControlStateNormal];
        }
    }else if(self.config.showStyle == YHOptionTagsStyle_FillColor){
        if(color){
            cell.btnTitle.backgroundColor = color;
        }
        else if (self.config.tagColor){
            cell.btnTitle.backgroundColor = self.config.tagColor;
        }
        else{
            cell.btnTitle.backgroundColor = [UIColor yh_background];
        }
    }
    
    if(tagStr &&
       self.config.selectTagsBlock &&
       [self.config.selectTags containsObject:tagStr]){
        cell.btnTitle.layer.borderWidth = 1;
        cell.btnTitle.layer.borderColor = [UIColor yh_orange].CGColor;
        [cell.btnTitle setTitleColor:[UIColor yh_orange] forState:UIControlStateNormal];
    }
    
    WS(weakSelf)
    if(self.config.canLongpressToDelete){
        [cell setCloseBlock:^(NSIndexPath *passIndexPath) {
            YHOptionTagsItem * tagD = weakSelf.tags[indexPath.row];
            if(weakSelf.config.deleteTagBlock){
                weakSelf.config.deleteTagBlock(tagD.tag,tagD.tagID,indexPath.row);
            }
            [weakSelf.tags removeObject:tagD];
            [weakSelf.collectionView deleteItemsAtIndexPaths:@[passIndexPath]];
        }];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == self.tags.count && self.config.addTagBlock){
        if(self.tags.count >= self.config.maxCount){
            YHHUDMsg([NSString stringWithFormat:@"最多%ld个标签",self.config.maxCount]);
            return;
        }
        WS(weakSelf)
        YHInputAlertView * inputAlertV = [YHInputAlertView new];
        inputAlertV.tapBtnToClose = NO;
        [inputAlertV addHeadTitle:@"输入标签"];
        [inputAlertV addBtnTitle:@"取消" action:^(YHAlertView * _Nonnull alertV) {
            [alertV popDismiss];
        }];
        [inputAlertV addBtnTitle:@"确定" action:^(YHAlertView * _Nonnull alertV) {
            YHInputAlertView * inputV = (YHInputAlertView *)alertV;
            if(IsNull(inputV.textField.text)){
                [inputV.textField yh_shake_zuoyou];
            }else{
                NSString * content = inputV.textField.text;
                content = [content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];;
                if(IsNull(content)){
                    YHHUDMsg(@"未输入内容");
                    return;
                }
                if(weakSelf.config.addTagBlock){
                    weakSelf.config.addTagBlock(content);
                }
                YHOptionTagsItem * item = [YHOptionTagsItem new];
                item.tag = content;
                [weakSelf.tags addObject:item];
                [weakSelf.collectionView reloadData];
                
                [alertV popDismiss];
            }
        }];
        [inputAlertV setShowConfigBlock:^(UITextField *passTextField, YHInputAlertView *passAlertView) {
            passTextField.yh_maxLength = 6;
            passTextField.placeholder = @"请输入要设置的标签";
            passTextField.text = @"";
        }];
        [inputAlertV popShow];
    }else{
        YHOptionTagsItem * tag = self.tags[indexPath.row];
        if(self.config.clickTagBlock){
            self.config.clickTagBlock(tag.tag,tag.tagID,indexPath.row);
        }
        if(self.config.selectTagsBlock){
            if([self.config.selectTags containsObject:tag.tag]){
                [self.config.selectTags removeObject:tag.tag];
            }else{
                [self.config.selectTags addObject:tag.tag];
            }
            [collectionView reloadData];
            self.config.selectTagsBlock(self.config.selectTags);
        }
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString * titleShow = @"";
    if(indexPath.row == self.tags.count && self.config.addTagBlock){
        titleShow = @"新增";
    }else{
        YHOptionTagsItem * tag = self.tags[indexPath.row];
        titleShow = tag.tag;
    }
    
    CGFloat maxw = CGRectGetWidth(collectionView.frame) - 10;
    CGFloat maxh = CGRectGetHeight(collectionView.frame);

    if(self.config.scrollDirection == UICollectionViewScrollDirectionHorizontal){
        CGRect frame = [titleShow boundingRectWithSize:CGSizeMake(FLT_MAX, maxh) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont yh_pfOfSize:10]} context:NULL];
        return CGSizeMake(CGRectGetWidth(frame) + 8, maxh);
    }
    CGRect frame = [titleShow boundingRectWithSize:CGSizeMake(maxw, FLT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont yh_pfOfSize:10]} context:NULL];
    return CGSizeMake(CGRectGetWidth(frame) + 20, CGRectGetHeight(frame)+8);
}

- (CGFloat)contentHeight{
    [self.collectionView layoutIfNeeded];
    if(self.collectionView.yh_width == 0){
        return 0;
    }
    CGFloat height = self.collectionView.contentSize.height;
    
    return height;
}

- (void)resetWithTags:(NSArray <NSString * >*)tags{
    NSMutableArray * list = [NSMutableArray new];
    [tags enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YHOptionTagsItem * item = [YHOptionTagsItem new];
        item.tag = obj;
        [list addObject:item];
    }];
    self.tags = list;
    [self reloadTagsView];

}

-(NSArray<NSString *> *)currentTags{
    NSMutableArray * tags = [NSMutableArray new];
    for(YHOptionTagsItem * item in self.tags){
        [tags addObject:item.tag];
    }
    return tags;
}
-(NSString *)currentTagsDes{
    return [[self currentTags] componentsJoinedByString:@","];
}

+ (YHOptionTagsView *)config:(void (^)(YHOptionTagsConfig * _Nonnull))config{
    YHOptionTagsView * tagsView = [YHOptionTagsView new];
    YHOptionTagsConfig * con = [YHOptionTagsConfig new];
    if(config){
        config(con);
    }
    tagsView.config = con;
    return tagsView;
}

- (void)resetWithTagCount:(NSInteger)count
                titleBlock:(nullable NSString * _Nonnull (^)(NSInteger))titleBlock
            colorBoxBlock:(nullable UIColor * _Nonnull (^)(NSInteger))colorBoxBlock
                tagIDBlock:(nullable NSString * _Nonnull (^)(NSInteger))tagIDBlock{
    
    NSMutableArray * list = [NSMutableArray new];
    for(NSInteger i = 0; i<count; i++){
        YHOptionTagsItem * item = [YHOptionTagsItem new];
        if(titleBlock){
            item.tag = titleBlock(i);
        }
        if(colorBoxBlock){
            item.color = colorBoxBlock(i);
        }
        if(tagIDBlock){
            item.tagID = tagIDBlock(i);
        }
        [list addObject:item];
    }
    self.tags = list;
    [self reloadTagsView];
}

@end
